package com.supermarket.seefood51.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.supermarket.seefood51.R;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import aclasdriver.AclasScale;


public class AclasScaleActivity extends Activity {
	private static final String tag = "AclasArmPosDBGScale";
	private AclasScale scale = null;
	private static boolean runflag;
	private Button bTare, bZero;
	private Button btnConfirm = null;
	private TextView tWei;

	private EditText etAddr;
	final private String strVer 	= "V2.104";//"V1.002";//
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scale);

		bTare = (Button) findViewById(R.id.button_tare);
		bTare.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(scale!=null){
					scale.SetTare();
				}
			}
		});

		btnConfirm = (Button)findViewById(R.id.button_confirm);
		btnConfirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String addr = etAddr.getText().toString();
				saveComAddr(addr);
				openScale();

			}
		});

		bZero = (Button) findViewById(R.id.button_zero);
		bZero.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(scale!=null){
					scale.SetZero();
				}
			}
		});

		tWei = (TextView) findViewById(R.id.textView_wei);
		tWei.setText("------");

		etAddr = (EditText)findViewById(R.id.etscaleAddr);
		Toast.makeText(this, "Version:"+strVer, Toast.LENGTH_SHORT).show();

		String addrString  = readComAddr();
		if(addrString!=null){
			etAddr.setText(addrString);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.d(tag, "scale onresume");
		openScale();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		AclasScaleActivity.runflag = false;

		//scale.close();
	}

	@Override
	protected void onDestroy(){
		super.onDestroy();
		AclasScaleActivity.runflag = false;
		if (scale != null){
			scale.close();
			scale = null;
		}
		Log.d("scale", "scale--->onDestroy");
	}

	private void openScale() {
		try {
			AclasScaleActivity.runflag	= false;

			try {
				Thread.sleep(320);

			} catch (Exception e) {
				// TODO: handle exception
			}
			String strAdd = etAddr.getText().toString();
			Log.d(tag, "scale new aclas scale:"+strAdd);
			//scale = new AclasScale(new File(strAdd), 9600, 0, AclasScale$ACLAS_SCALE_PROTOCOL_TYPE.scale_protocol_autoupload);
			scale = new AclasScale(new File(strAdd), 9600, 0, AclasScale.ACLAS_SCALE_PROTOCOL_TYPE.scale_protocol_autoupload);

		}
		catch (SecurityException e) {
			// TODO Auto-generated catch block
			scale	= null;
			Toast.makeText(this,"OpenScale exception", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		catch (Exception e) {
			// TODO: handle exception
			scale	= null;
			Toast.makeText(this,"OpenScale exception", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		if(scale!=null){
			Log.d(tag, "scale start run thread");
			//scale.setAclasScaleListener(arg0)
			scale.setAclasScaleListener(new AclasScale.AclasScaleListener(){
				//			    scale.setAclasScaleListener(new AclasScale$AclasScaleListener(){
				public void OnError(int code){
					Message msg = myhandle.obtainMessage();
					msg.arg1 = 0;
					if(code==AclasScale.CODENEEDUPDATE){

						AclasScaleActivity.runflag = false;
						msg.arg1 = 1;
						Log.d(tag, "AclasScale$AclasScaleListener onError CODENEEDUPDATE---------");
//		    		        myhandle.sendEmptyMessage(0);
						myhandle.sendMessage(msg);

						//Toast.makeText(AclasScaleActivity.this,"The Firmware need update", Toast.LENGTH_LONG).show();
					}else if(code==AclasScale.NODATARECEIVE){

						AclasScaleActivity.runflag = false;
						msg.arg1 = 2;
						Log.d(tag, "AclasScale$AclasScaleListener onError NODATARECEIVE---------");
						myhandle.sendMessage(msg);
					}
				}
			});
			AclasScaleActivity.runflag = true;
			scale_thread Scalethread = new scale_thread();
			Scalethread.start();
		}else{
			Log.e(tag, "scale null!!!!!!!!!!!!!!!!!!!");
		}
	}
	class scale_thread extends Thread
	{
		public void run()
		{
			AclasScaleActivity.runflag = true;
			while(AclasScaleActivity.runflag&&scale!=null)
			{
				byte[] wei = scale.GetWeight();

				if(wei != null)
				{
					Message msg_read = gui_show.obtainMessage();
					msg_read.arg1 = 1;
					msg_read.obj = new String(new String(wei));
					gui_show.sendMessage(msg_read);
				}
				try {
					sleep(20);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}

		}

		Handler gui_show = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch(msg.arg1)
				{
					case 1:
						tWei.setText((String)msg.obj);
						break;
				}
			}
		};

		@Override
		public synchronized void start() {
			// TODO Auto-generated method stub
			super.start();
		}
	}

	public Handler myhandle = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.arg1) {
				case 1:
					Toast.makeText(AclasScaleActivity.this,"The Firmware need update", Toast.LENGTH_LONG).show();
					break;
				case 2:
					Toast.makeText(AclasScaleActivity.this,"There is no data!", Toast.LENGTH_LONG).show();
					break;

				default:
					Toast.makeText(AclasScaleActivity.this,"Unknown error", Toast.LENGTH_LONG).show();
					break;
			}
		}
	};

	/*
	 * save com address in txt file;
	 */
	private void saveComAddr(String name) {
		if(name.length()>0){
			final String LOG_FILE = "/storage/sdcard0/Download/settings.txt";
			File file = new File(LOG_FILE);
			try {

				if(file.exists()){
					file.delete();
				}
				file.createNewFile();
				FileWriter writer = new FileWriter(file, true);
				writer.write(name, 0,name.length());
				writer.close();
			} catch (Exception e) {

				// TODO: handle exception
				Log.e(tag, "saveComAddr error:"+e.toString());
			}
		}
	}

	private String readComAddr() {
		final String LOG_FILE = "/storage/sdcard0/Download/settings.txt";
		String addrName = null;
		File file = new File(LOG_FILE);
		if(file.exists()){

			try {
				char[] buffer = new char[1024];

				FileReader reader = new FileReader(file);
				int iCnt = reader.read(buffer);
				if( -1!=iCnt ){
					addrName = String.valueOf(buffer, 0, iCnt);
				}

				reader.close();
			} catch (Exception e) {
				// TODO: handle exception
				Log.e(tag, "readComAddr error:"+e.toString());
			}

		}
		return addrName;
	}
}
